<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\LocalDeviceInfoModel;
use app\service\cache\LocalDeviceInfoCacheService;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\service\UserBaseService;
use share\utils\Helper;

class LocalDeviceInfoService extends BaseModelService
{

    const USER_LOCAL_DEVICE_INFO_MAX_NUM = 128;

    public static function getModel()
    {
        return new LocalDeviceInfoModel;
    }



    // public static function getAllByAVendor($vendor)
    // {
    //     $appInfo = AppInfoTableService::getByFilter(['vendor' => $vendor]);
    //     if (empty($appInfo)) {
    //         throw new ApiException("app is not allow pay", ErrnoPlus::COMMON_ERROR);
    //     }
    //     $res = self::getAllByFilter(["aid" => $appInfo['id']]);
    //     $mids = Helper::arraySmartUnique(array_column($res, 'mid'));
    //     if (count($mids) < 1) {
    //         return null;
    //     }
    //     $merchantInfo = MerchantInfoTableService::getAll($mids);
    //     return $merchantInfo;
    // }

    // public static function getAllByUserId($uids)
    // {
    //     return LocalDeviceInfoCacheService::getAllByFilter(["uid" => $uids]);
    // }

    public static function delLocalDevice($param)
    {
        $userId = $param['userId'];
        $userInfo = UserBaseService::getByUserId($userId);
        if (!$userInfo) {
            throw new ApiException("user not found", ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $uid =  $userInfo['id'];
        $filter = [
            'uid' => $uid,
            'serial_number' => ['in', $param['serialNos']],
        ];
        self::delByFilter($filter);
        LocalDeviceInfoCacheService::del(['uid' => $uid]);
    }

    public static function addDevice($param, $checkOrigin = true)
    {
        if(isset($param['uid'])) {
            $uid = $param['uid'];
        }
        else if(isset($param['userId'])){
            $userId = $param['userId'];
            $userInfo = UserBaseService::getByUserId($userId);
            if (!$userInfo) {
                throw new ApiException("user not found", ErrnoPlus::COMMON_INVALID_INPUT);
            }
            $uid =  $userInfo['id'];
        }
        else{
            throw new ApiException("user info lost", ErrnoPlus::COMMON_INVALID_INPUT);
        }

        $serialNo = $param['serialNo'];
        if ($checkOrigin) {
            $res = self::getByFilter(["uid" => $uid, "serial_number" => $serialNo]);  
            if (!empty($res)) {
                throw new ApiException("this device already exists", ErrnoPlus::LOCAL_DEVICE_EXISTS);
            }
        }
        $devices = self::getAllByFilter(["uid" => $uid]);
        if (count($devices) >= self::USER_LOCAL_DEVICE_INFO_MAX_NUM) {
            throw new ApiException("you have too many device in current account");
        }
        $data = [
            "uid" => $uid,
            "serial_number" => $param["serialNo"],
            "ip" => $param["ip"],
            "port" => intval($param["port"]),
            "nick_name" => $param["nickName"],
            "user_name" => $param["userName"],
            "password" => $param["password"],
            "type" => $param["type"]
        ];
        self::add($data);
        LocalDeviceInfoCacheService::del(['uid' => $uid]);
    }

    public static function updateDevice($param)
    {
        $userId = $param['userId'];
        $userInfo = UserBaseService::getByUserId($userId);
        if (!$userInfo) {
            throw new ApiException("user not found", ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $uid =  $userInfo['id'];
        unset($param['userId']);
        $param['uid'] = $uid;
        $serialNo = $param['serialNo'];
        $res = self::getByFilter(["uid" => $uid, "serial_number" => $serialNo]);
        if (empty($res)) { // 不存在时  新增
            return self::addDevice($param, false);
        }
        $data = [
            "serial_number" => $param["serialNo"],
            "ip" => $param["ip"],
            "port" => intval($param["port"]),
            "nick_name" => $param["nickName"],
            "user_name" => $param["userName"],
            "password" => $param["password"],
            "type" => $param["type"]
        ];
        $updateField = [];
        foreach ($data as $key => $val) {
            if ($val !== $res[$key]) {
                $updateField[$key] = $val;
            }
        }
        if (count($updateField) > 0) {
            self::update($res['id'], $updateField);
            LocalDeviceInfoCacheService::del(['uid' => $userId]);
        }
    }
}
